package ua.in.hut;

import java.sql.*;
import java.util.*;
import static ua.in.hut.AuthException.*;
import ua.org.ass.*;

/**
 *
 * @author frick.ua
 */
public class Authenticator {

	public static String login(String uHash, String host, String userAgent)
			  throws SQLException, AuthException {
		String sessionID = null;
		if (uHash != null) {
			DB db = DB.connect("Hut");
			ResultSet resultSet = db.executeQuery("SELECT rid, uname FROM users "
					  + "WHERE md5(uname || upass) = ?;", uHash);
			resultSet.beforeFirst();
			if (resultSet.next()) {
				Object uRid = resultSet.getObject("rid");
				ResultSet con = db.executeQuery("SELECT rid FROM ucon "
					  + "WHERE pid = ? AND uagent = ? AND uhost = ?;", uRid, userAgent, host);
				con.beforeFirst();
				if (con.next()) {
					throw new AuthException(ALREADY_AUTHENTICATE, "Вже авторизовано.");
				}
				ResultSet rs = db.executeInsert("INSERT INTO ucon(pid, uhost, uagent) VALUES(?, ?, ?)",
						  new String[]{"rid"}, uRid, host, userAgent);
				if (rs.next()) {
					sessionID = rs.getString("rid");
				}
			} else {
				throw new AuthException("Не знайдено користувача за хеш-кодом.");
			}
		}
		return sessionID;
	}

	public static boolean checkAuthentication(String sessionID, String clientHost, String userAgent) throws SQLException {
		DB db = DB.connect("Hut");
		ResultSet con = db.executeQuery("SELECT rid FROM ucon "
					  + "WHERE rid = ? AND uagent = ? AND uhost = ?;", UUID.fromString(sessionID), userAgent, clientHost);
		return con.next();
	}

}
